package day21;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 *
 * RandomAccessFileDemo.java
 * @author wangbiao<br/>
 *         email:785497344@qq.com
 * @description 随机读写文件类，可以实现文件的随机分段读取和写入。并且还能读已有数据进行修改
 * @since 1.0.0
 * @date 2013-6-30下午5:21:34
 *
 */
public class RandomAccessFileDemo {

	public static void main(String[] args) {
		// writeFile();
		skipWriteFile();
		readFile();
		skipReadFile();
	}

	public static void skipReadFile() {
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile("accessFile", "r");
			// 跳过指定的字节数，只能往后面跳
			raf.skipBytes(10);
			// 指针偏移到指定的位置，开始读取
			raf.seek(10);
			byte[] b = new byte[6];
			raf.read(b);
			System.out.println("name" + new String(b));

			int age = raf.readInt();
			System.out.println("age" + age);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != raf) {
					raf.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void readFile() {
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile("accessFile", "r");
			byte[] b = new byte[6];
			raf.read(b);
			System.out.println("name" + new String(b));

			int age = raf.readInt();
			System.out.println("age" + age);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != raf) {
					raf.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void skipWriteFile() {
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile("accessFile", "rw");
			raf.seek(20);
			raf.write("赵六".getBytes());
			// 直接写入一个4个字节的int值
			raf.writeInt(78);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != raf) {
				try {
					raf.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public static void writeFile() {
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile("accessFile", "rw");
			raf.write("李四".getBytes());
			// 直接写入一个4个字节的int值
			raf.writeInt(56);

			raf.write("王武".getBytes());
			raf.writeInt(102);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != raf) {
				try {
					raf.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
